package controller

import (
	"encoding/json"
	"time"

	. "gddgame.cc/galaxy/common/dsl/game"
	. "gddgame.cc/galaxy/common/dsl/game/attr"
	. "gddgame.cc/galaxy/common/dsl/game/config"
	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/project/star/star/model"
	"gddgame.cc/galaxy/utils"
	"gddgame.cc/galaxy/utils/def"
)

// 更新所有人的军阶
func UpdateAllGrade(context def.Context) error {
	var users []model.User
	var err error
	var c int64
	var topUserMap map[int]bool
	c, err = model.UserModel.Query().Where(">", "point", model.MaxWeekPoint).Count()
	if err != nil {
		return SystemExceptionDetail("查找军阶信息失败", err)
	}
	limit := int(c / 10)
	if limit > 0 {
		if _, err = model.UserModel.Query().Where(">", "point", model.MaxWeekPoint).Desc("point").Limit(0, limit).Find(&users); err != nil {
			return SystemExceptionDetail("查找用户信息失败", err)
		}
		topUserMap = make(map[int]bool, len(users))
		for key := range users {
			topUserMap[users[key].Id] = true
		}
	} else {
		topUserMap = make(map[int]bool)
	}

	page := 0
	size := 50
	data := make(map[string]interface{}, 3)
	// 涉及到军阶变动的人
	query := model.UserModel.Query().Where(">", "point", 0).Where(">", "last_point", 0)

Page:
	page += 1
	if _, err = query.Page(page, size).Find(&users); err != nil {
		return SystemExceptionDetail("查找用户信息失败", err)
	}

	if len(users) > 0 {
		for _, user := range users {
			user.ComputeGrade(topUserMap)
			data["point"] = user.Point
			data["last_point"] = user.LastPoint
			data["grade"] = user.Grade
			_, _ = model.UserModel.PK(user.Id).Update(data)
		}
		goto Page
	}
	return nil
}

func UpdateUserAttr(context def.Context) error {
	// 获取当前最高配置
	var config SettingConfig
	var ok bool
	var err error
	configModel, err := Env.GetModel(SettingConfigName)
	if err != nil {
		return err
	}
	if ok, err = configModel.PK("MaxObjectAttr").One(&config); !ok {
		return EmptyExceptionDetail("查找配置失败", err)
	}
	var attr []int
	if err := json.Unmarshal(utils.ToBytes(config.Value), &attr); err != nil {
		return err
	}
	// 获取昨天所有修改账号用户
	number := 20
	query := model.UserModel.Query().Where(">=", "update_time", time.Now().AddDate(0, 0, -1))
	count, err := query.Count()
	if err != nil {
		return SystemExceptionDetail("查找用户失败", err)
	}
	if count > 0 {
		for page := 1; page <= int(count)/number+1; page++ {
			var users []model.User
			if _, err = query.Page(page, number).Find(&users); err != nil {
				return SystemExceptionDetail("查找用户失败", err)
			}
			for key := range users {
				data, err := GetUserDetailInfo(context, &users[key], DefaultLanguage)
				if err != nil {
					return SystemExceptionDetail("查找用户失败", err)
				}
				baseAttr := AttrEffectSlice{}
				baseAttr = baseAttr.Merge(data.BaseAttr)
				baseAttr = baseAttr.Merge(data.BadgeAttr)
				baseAttr = baseAttr.Merge(data.ItemAttr)
				for _, value := range baseAttr {
					if byte(len(attr)) <= value.Index {
						attr = append(attr, make([]int, int(value.Index)-len(attr)+1)...)
						attr[value.Index] = value.Value
					} else if value.Value > attr[value.Index] {
						attr[value.Index] = value.Value
					}
				}
			}
		}
	}
	b, err := json.Marshal(&attr)
	if err != nil {
		return err
	}
	config.Value = string(b)
	// 保存配置文件
	_, err = configModel.PK("MaxObjectAttr").Save(false, &config)
	if err != nil {
		return SystemExceptionDetail("保存配置失败", err)
	}
	// 初始化等级信息
	if _, err := model.InitConfig(&config); err != nil {
		return err
	}
	if err := Env.SetConfig("MaxObjectAttr", attr); err != nil {
		return err
	}
	return nil
}
